package com.um.jdy.common.commons.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.um.jdy.common.charge.dao.OrderCommissionDao;
import com.um.jdy.common.charge.dao.OrderSharingDao;
import com.um.jdy.common.charge.dao.OrderSharingUserDao;
import com.um.jdy.common.charge.entity.po.OrderCommission;
import com.um.jdy.common.charge.entity.po.OrderSharing;
import com.um.jdy.common.charge.entity.po.OrderSharingUser;
import com.um.jdy.common.commons.service.CommissionService;
import com.um.jdy.common.device.dao.StationDao;
import com.um.jdy.common.device.dao.StationSharingDao;
import com.um.jdy.common.device.entity.po.Station;
import com.um.jdy.common.device.entity.po.StationSharing;
import com.um.jdy.common.finance.dao.MerchantBillDao;
import com.um.jdy.common.finance.dao.PlatformBillDao;
import com.um.jdy.common.finance.dao.PlatformProfitBillDao;
import com.um.jdy.common.finance.entity.po.MerchantBill;
import com.um.jdy.common.finance.entity.po.PlatformProfitBill;
import com.um.jdy.common.finance.enums.FinancialEnum;
import com.um.jdy.common.member.enums.MemberEnum;
import com.um.jdy.common.month.dao.CardOrderCommissionDao;
import com.um.jdy.common.month.entity.po.CardOrderCommission;
import com.um.jdy.common.platform.dao.MerchantDao;
import com.um.jdy.common.platform.entity.po.Merchant;
import com.um.springboot.starter.utils.OrderUtil;
import com.um.springboot.starter.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 邓南辉
 * 日期 2023/6/19
 * 版权所有 广州优匠科技有限公司
 */
@Service

@Slf4j
public class CommissionServiceImpl implements CommissionService {


    @Autowired
    MerchantBillDao merchantBillDao;

    @Autowired
    PlatformBillDao platformBillDao;

    @Autowired
    PlatformProfitBillDao platformProfitBillDao;

    @Autowired
    OrderCommissionDao orderCommissionDao;

    @Autowired
    OrderSharingDao orderSharingDao;

    @Autowired
    OrderSharingUserDao orderSharingUserDao;

    @Autowired
    StationSharingDao stationSharingDao;

    @Autowired
    CardOrderCommissionDao cardOrderCommissionDao;

    @Autowired
    StationDao stationDao;

    @Autowired
    MerchantDao merchantDao;


    /**
     * 计算订单的佣金
     *
     * @param orderId 订单ID
     * @return 返回 充电利润（利润(分)公式=充电金额-所有佣金）
     */
    public int calcCommission(String orderId, Date createTime, String orderNo, String outTradeNo, int chargeAmount){

        // merchantBillDao.deleteRow("order_no",orderNo);
        // platformBillDao.deleteRow("order_no",orderNo);
        // platformProfitBillDao.deleteRow("order_no",orderNo);
        // orderCommissionDao.deleteRow("charge_order_id",orderId);

        if(chargeAmount <= 0)
            return 0;

        OrderSharing orderSharing = orderSharingDao.getRow("charge_order_id",orderId);
        if(orderSharing == null){//复制不存在，不分佣
            return chargeAmount;
        }

        String RateRemark = "";
        int sortNo = 1;

        //分成商户
        int totalSharingCommission = 0;
        //分成商户总比例
        double totalSharingRate = 0;

        List<OrderSharingUser> sharingUsers = orderSharingUserDao.getRows(new String[]{"charge_order_id"},new Object[]{orderId},new String[]{},new String[]{});
        for(int index = 0;index < sharingUsers.size();index ++){
            OrderSharingUser item = sharingUsers.get(index);
            double sharingRate = NumberUtil.div(item.getCommissionRate().doubleValue(), 100);

                if (sharingRate >= 0) {

                    int sharingCommission = (int)NumberUtil.mul(chargeAmount, sharingRate);

                    MerchantBill merchantBill = new MerchantBill();
                    merchantBill.setPlatformMerchantId(item.getPlatformMerchantId());
                    merchantBill.setComId(orderSharing.getComId());
                    merchantBill.setNo(OrderUtil.getOrderNo());
                    merchantBill.setOutTradeNo(outTradeNo);
                    merchantBill.setOrderNo(orderNo);
                    merchantBill.setAmount(sharingCommission);
                    merchantBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
                    merchantBill.setEvent(FinancialEnum.MerchantBillEvent.Commission.name());
                    merchantBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                    merchantBill.setCreateTime(createTime);
                    merchantBillDao.saveRow(merchantBill);

                    totalSharingCommission += sharingCommission;
                    totalSharingRate += sharingRate;

                    //TODO 记录订单佣金
                    RateRemark =  NumberUtil.div(chargeAmount,100) + " * " + formatRate(sharingRate);

                    saveOrderCommission(orderId,orderSharing.getComId(),item.getPlatformMerchantId(),sharingCommission,
                            item.getCommissionRate(),RateRemark,MemberEnum.UserType.sharing.name(),sortNo);

                    sortNo ++;
                }
        }

        //运营商
        int merchantCommission = 0;
        double merchantRate = NumberUtil.div(orderSharing.getMerchantRate().doubleValue(), 100);
        if (merchantRate > 0 && !StrUtil.isEmpty(orderSharing.getMerchantId())) {

            merchantCommission = (int)NumberUtil.mul(chargeAmount, merchantRate);
            merchantCommission = merchantCommission - totalSharingCommission;


            MerchantBill merchantBill = new MerchantBill();
            merchantBill.setPlatformMerchantId(orderSharing.getMerchantId());
            merchantBill.setComId(orderSharing.getComId());
            merchantBill.setNo(OrderUtil.getOrderNo());
            merchantBill.setOutTradeNo(outTradeNo);
            merchantBill.setOrderNo(orderNo);
            merchantBill.setAmount(merchantCommission);
            merchantBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
            merchantBill.setEvent(FinancialEnum.MerchantBillEvent.Commission.name());
            merchantBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
            merchantBill.setCreateTime(createTime);
            merchantBillDao.saveRow(merchantBill);

            //TODO 记录订单佣金
            RateRemark =  NumberUtil.div(chargeAmount,100) + " * (" + formatRate(merchantRate) + " - " + formatRate(totalSharingRate) +")";

            saveOrderCommission(orderId, orderSharing.getComId(),orderSharing.getMerchantId(), merchantCommission,
                    orderSharing.getMerchantRate(),RateRemark,MemberEnum.UserType.merchant.name(),sortNo);

            sortNo ++;
        }




        //上级运营商
        int parentCommission = 0;
        if(!StringUtil.isEmpty(orderSharing.getParentId())){
            double parentRate = NumberUtil.div(orderSharing.getParentRate().doubleValue(), 100);
            parentCommission = NumberUtil.sub(NumberUtil.mul(chargeAmount, parentRate), merchantCommission, totalSharingCommission).intValue();

            MerchantBill merchantBill = new MerchantBill();
            merchantBill.setPlatformMerchantId(orderSharing.getParentId());
            merchantBill.setComId(orderSharing.getComId());
            merchantBill.setNo(OrderUtil.getOrderNo());
            merchantBill.setOutTradeNo(outTradeNo);
            merchantBill.setOrderNo(orderNo);
            merchantBill.setAmount(parentCommission);
            merchantBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
            merchantBill.setEvent(FinancialEnum.MerchantBillEvent.Commission.name());
            merchantBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
            merchantBill.setCreateTime(createTime);
            merchantBillDao.saveRow(merchantBill);

            //TODO 记录订单佣金
            RateRemark =  NumberUtil.div(chargeAmount,100) + " * (" + formatRate(parentRate) + " - " + formatRate(merchantRate) + ")";

            saveOrderCommission(orderId,orderSharing.getComId(),orderSharing.getParentId(),parentCommission,
                    orderSharing.getParentRate(),RateRemark,MemberEnum.UserType.merchant.name(),sortNo);

            sortNo ++;
        }

        int profit = chargeAmount - parentCommission - merchantCommission - totalSharingCommission;
        //添加平台收益流水-充电佣金
        if(profit > 0) {

            PlatformProfitBill profitBill = new PlatformProfitBill();
            profitBill.setComId(orderSharing.getComId());
            profitBill.setOutTradeNo(outTradeNo);
            profitBill.setOrderNo(orderNo);
            profitBill.setAmount(profit);
            profitBill.setCreateTime(createTime);
            profitBill.setType(FinancialEnum.IncomeOrExpend.Income.name());
            profitBill.setStatus(FinancialEnum.BillStatus.Effective.name());
            profitBill.setEvent(FinancialEnum.PlatformProfitBillEvent.Commission.name());
            profitBill.setNo(StrUtil.builder(cn.hutool.core.date.DateUtil.date().toString(DatePattern.PURE_DATETIME_MS_PATTERN), RandomUtil.randomNumbers(4)).toString());
            platformProfitBillDao.saveRow(profitBill);
        }

        return profit;

    }

    private String formatRate(Double value){
        DecimalFormat format = new DecimalFormat("##.##");
        return format.format(value);
    }

//    public static void main(String[] args){
//        DecimalFormat format = new DecimalFormat("##.##");
//        System.out.println(format.format(0.120000000000000001));
//    }

    /**
     * 佣金退款
     * @param orderId
     * @param createTime
     * @param orderNo
     * @param outTradeNo
     * @param refundAmount 退款金额
     * @param chargeAmount 退款后的订单金额，用于更新订单分佣说明
     * @return 订单利润
     */
    @Override
    public int refundCommission(String orderId, Date createTime, String orderNo, String outTradeNo, int refundAmount,int chargeAmount) {
        if(refundAmount <= 0)
            return 0;

        OrderSharing orderSharing = orderSharingDao.getRow("charge_order_id",orderId);
        if(orderSharing == null){//复制不存在，不分佣
            return refundAmount;
        }

        String RateRemark = "";
        int sortNo = 1;

        //分成商户
        int totalSharingCommission = 0;
        //分成商户总比例
        double totalSharingRate = 0;
        List<OrderSharingUser> sharingUsers = orderSharingUserDao.getRows(new String[]{"charge_order_id"},new Object[]{orderId},new String[]{},new String[]{});
        for(int index = 0;index < sharingUsers.size();index ++){
            OrderSharingUser item = sharingUsers.get(index);
            double sharingRate = NumberUtil.div(item.getCommissionRate().doubleValue(), 100);

            if (sharingRate >= 0) {

                int sharingCommission = (int)NumberUtil.mul(refundAmount, sharingRate);

                MerchantBill merchantBill = new MerchantBill();
                merchantBill.setPlatformMerchantId(item.getPlatformMerchantId());
                merchantBill.setComId(orderSharing.getComId());
                merchantBill.setNo(OrderUtil.getOrderNo());
                merchantBill.setOutTradeNo(outTradeNo);
                merchantBill.setOrderNo(orderNo);
                merchantBill.setAmount(sharingCommission);
                merchantBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());//收入支出类型：0-收入，1-支出
                merchantBill.setEvent(FinancialEnum.MerchantBillEvent.OrderRefund.name());
                merchantBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                merchantBill.setCreateTime(createTime);
                merchantBillDao.saveRow(merchantBill);

                totalSharingCommission += sharingCommission;
                totalSharingRate += sharingRate;

                //TODO 记录订单佣金
                RateRemark =  NumberUtil.div(chargeAmount,100) + " * " + formatRate(sharingRate);

                saveOrderCommission(orderId,orderSharing.getComId(),item.getPlatformMerchantId(),sharingCommission,
                        item.getCommissionRate(),RateRemark,MemberEnum.UserType.sharing.name(),sortNo);

                sortNo ++;
            }
        }

        //运营商
        int merchantCommission = 0;
        double merchantRate = NumberUtil.div(orderSharing.getMerchantRate().doubleValue(), 100);
        if (merchantRate > 0 && !StrUtil.isEmpty(orderSharing.getMerchantId())) {

            merchantCommission = (int)NumberUtil.mul(refundAmount, merchantRate);
            merchantCommission = merchantCommission - totalSharingCommission;


            MerchantBill merchantBill = new MerchantBill();
            merchantBill.setPlatformMerchantId(orderSharing.getMerchantId());
            merchantBill.setComId(orderSharing.getComId());
            merchantBill.setNo(OrderUtil.getOrderNo());
            merchantBill.setOutTradeNo(outTradeNo);
            merchantBill.setOrderNo(orderNo);
            merchantBill.setAmount(merchantCommission);
            merchantBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());//收入支出类型：0-收入，1-支出
            merchantBill.setEvent(FinancialEnum.MerchantBillEvent.OrderRefund.name());
            merchantBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
            merchantBill.setCreateTime(createTime);
            merchantBillDao.saveRow(merchantBill);

            //TODO 记录订单佣金
            RateRemark =  NumberUtil.div(chargeAmount,100) + " * (" + formatRate(merchantRate) + " - " + formatRate(totalSharingRate) +")";

            saveOrderCommission(orderId, orderSharing.getComId(),orderSharing.getMerchantId(), merchantCommission,
                    orderSharing.getMerchantRate(),RateRemark,MemberEnum.UserType.merchant.name(),sortNo);

            sortNo ++;
        }




        //上级运营商
        int parentCommission = 0;
        if(!StringUtil.isEmpty(orderSharing.getParentId())){
            double parentRate = NumberUtil.div(orderSharing.getParentRate().doubleValue(), 100);
            parentCommission = NumberUtil.sub(NumberUtil.mul(refundAmount, parentRate), merchantCommission, totalSharingCommission).intValue();

            MerchantBill merchantBill = new MerchantBill();
            merchantBill.setPlatformMerchantId(orderSharing.getParentId());
            merchantBill.setComId(orderSharing.getComId());
            merchantBill.setNo(OrderUtil.getOrderNo());
            merchantBill.setOutTradeNo(outTradeNo);
            merchantBill.setOrderNo(orderNo);
            merchantBill.setAmount(parentCommission);
            merchantBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());//收入支出类型：0-收入，1-支出
            merchantBill.setEvent(FinancialEnum.MerchantBillEvent.OrderRefund.name());
            merchantBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
            merchantBill.setCreateTime(createTime);
            merchantBillDao.saveRow(merchantBill);

            //TODO 记录订单佣金
            RateRemark =  NumberUtil.div(chargeAmount,100) + " * (" + formatRate(parentRate) + " - " + formatRate(merchantRate) + ")";

            saveOrderCommission(orderId,orderSharing.getComId(),orderSharing.getParentId(),parentCommission,
                    orderSharing.getParentRate(),RateRemark,MemberEnum.UserType.merchant.name(),sortNo);

            sortNo ++;
        }


        int profit = refundAmount - parentCommission - merchantCommission - totalSharingCommission;
        //添加平台收益流水-充电佣金
        if(profit > 0) {
            PlatformProfitBill profitBill = new PlatformProfitBill();
            profitBill.setComId(orderSharing.getComId());
            profitBill.setOutTradeNo(outTradeNo);
            profitBill.setOrderNo(orderNo);
            profitBill.setAmount(profit);
            profitBill.setCreateTime(createTime);
            profitBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());
            profitBill.setStatus(FinancialEnum.BillStatus.Effective.name());
            profitBill.setEvent(FinancialEnum.PlatformProfitBillEvent.OrderRefund.name());
            profitBill.setNo(StrUtil.builder(cn.hutool.core.date.DateUtil.date().toString(DatePattern.PURE_DATETIME_MS_PATTERN), RandomUtil.randomNumbers(4)).toString());
            platformProfitBillDao.saveRow(profitBill);
        }

        return profit;
    }

    /**
     * 记录订单佣金
     * @param userId orderId 订单ID
     * @param userId 用户ID(代理商、运营商、业务员）
     * @param commission 佣金
     * @param radio 佣金比例
     * @param RateRemark 佣金比例说明
     * @param userType 类型:agent-代理商 merchant-运营商 salesman-业务员
     */
    private void saveOrderCommission(String orderId,String comId,String userId,int commission,int radio,String RateRemark,String userType,int sortNo){
        OrderCommission entity = orderCommissionDao.getRow(new String[]{"com_id","charge_order_id","platform_user_id"},new Object[]{comId,orderId,userId});
        if(entity == null){
            entity = new OrderCommission();
            entity.setComId(comId);
            entity.setChargeOrderId(orderId);
            entity.setPlatformUserId(userId);

            entity.setCommissionRate(radio);
            entity.setRateRemark(RateRemark);
            entity.setUserType(userType);
            entity.setSortNo(sortNo);
            entity.setCommission(commission);
            entity.setCreateTime(DateUtil.date());
        }else{
            if(entity.getRateRemark().startsWith("首次佣金")){
                entity.setRateRemark(entity.getRateRemark() + " - 退款佣金：" + formatRate(commission / 100.0));
            }else {
                entity.setRateRemark("首次佣金：" + formatRate(entity.getCommission() / 100.0) + " - 退款佣金：" + formatRate(commission / 100.0));
            }
            entity.setCommission(entity.getCommission() - commission);
            entity.setCreateTime(DateUtil.date());
        }

        orderCommissionDao.saveRow(entity);
    }




    /**
     * 计算月卡订单的佣金
     *
     * @param orderId 订单ID
     * @return 返回 月卡利润（利润(分)公式=月卡金额-所有佣金）
     */
    @Override
    public int calcMonthCardCommission(String orderId,String stationId, Date createTime, String orderNo, String outTradeNo, int payAmount){
        if(payAmount <= 0)
            return 0;

        Station station = stationDao.getRow(stationId);
        if(station == null){
            return payAmount;
        }

        String RateRemark = "";
        int sortNo = 1;

        //分成商户
        int totalSharingCommission = 0;
        //分成商户总比例
        double totalSharingRate = 0;

        List<StationSharing> stationSharings = stationSharingDao.getRows(new String[]{"device_station_id"},new Object[]{stationId},new String[]{},new String[]{});
        for(int index = 0;index < stationSharings.size();index ++){
            StationSharing item = stationSharings.get(index);
            double sharingRate = NumberUtil.div(item.getCommissionRate().doubleValue(), 100);

            if (sharingRate >= 0) {

                int sharingCommission = (int)NumberUtil.mul(payAmount, sharingRate);

                MerchantBill merchantBill = new MerchantBill();
                merchantBill.setPlatformMerchantId(item.getPlatformMerchantId());
                merchantBill.setComId(station.getComId());
                merchantBill.setNo(OrderUtil.getOrderNo());
                merchantBill.setOutTradeNo(outTradeNo);
                merchantBill.setOrderNo(orderNo);
                merchantBill.setAmount(sharingCommission);
                merchantBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
                merchantBill.setEvent(FinancialEnum.MerchantBillEvent.MonthCommission.name());
                merchantBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                merchantBill.setCreateTime(createTime);
                merchantBillDao.saveRow(merchantBill);

                totalSharingCommission += sharingCommission;
                totalSharingRate += sharingRate;

                //TODO 记录订单佣金
                RateRemark =  NumberUtil.div(payAmount,100) + " * " + formatRate(sharingRate);

                saveMonthCardOrderCommission(orderId,station.getComId(),item.getPlatformMerchantId(),sharingCommission,
                        item.getCommissionRate(),RateRemark,MemberEnum.UserType.sharing.name(),sortNo);

                sortNo ++;
            }
        }

        //运营商
        int merchantCommission = 0;
        double merchantRate = NumberUtil.div(station.getCommissionRate().doubleValue(), 100);
        if (merchantRate > 0 && !StrUtil.isEmpty(station.getPlatformMerchantId())) {

            merchantCommission = (int)NumberUtil.mul(payAmount, merchantRate);
            merchantCommission = merchantCommission - totalSharingCommission;


            MerchantBill merchantBill = new MerchantBill();
            merchantBill.setPlatformMerchantId(station.getPlatformMerchantId());
            merchantBill.setComId(station.getComId());
            merchantBill.setNo(OrderUtil.getOrderNo());
            merchantBill.setOutTradeNo(outTradeNo);
            merchantBill.setOrderNo(orderNo);
            merchantBill.setAmount(merchantCommission);
            merchantBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
            merchantBill.setEvent(FinancialEnum.MerchantBillEvent.MonthCommission.name());
            merchantBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
            merchantBill.setCreateTime(createTime);
            merchantBillDao.saveRow(merchantBill);

            //TODO 记录订单佣金
            RateRemark =  NumberUtil.div(payAmount,100) + " * (" + formatRate(merchantRate) + " - " + formatRate(totalSharingRate) +")";

            saveMonthCardOrderCommission(orderId, station.getComId(),station.getPlatformMerchantId(), merchantCommission,
                    station.getCommissionRate(),RateRemark,MemberEnum.UserType.merchant.name(),sortNo);

            sortNo ++;
        }


        Merchant merchant = merchantDao.getEntity(station.getPlatformMerchantId());
        //上级运营商
        int parentCommission = 0;
        if(merchant != null && !StringUtil.isEmpty(merchant.getParentId())){

            Merchant parent = merchantDao.getEntity(merchant.getParentId());

            double parentRate = NumberUtil.div(parent.getCommissionRate().doubleValue(), 100);
            parentCommission = NumberUtil.sub(NumberUtil.mul(payAmount, parentRate), merchantCommission, totalSharingCommission).intValue();

            MerchantBill merchantBill = new MerchantBill();
            merchantBill.setPlatformMerchantId(merchant.getParentId());
            merchantBill.setComId(station.getComId());
            merchantBill.setNo(OrderUtil.getOrderNo());
            merchantBill.setOutTradeNo(outTradeNo);
            merchantBill.setOrderNo(orderNo);
            merchantBill.setAmount(parentCommission);
            merchantBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
            merchantBill.setEvent(FinancialEnum.MerchantBillEvent.MonthCommission.name());
            merchantBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
            merchantBill.setCreateTime(createTime);
            merchantBillDao.saveRow(merchantBill);

            //TODO 记录订单佣金
            RateRemark =  NumberUtil.div(payAmount,100) + " * (" + formatRate(parentRate) + " - " + formatRate(merchantRate) + ")";

            saveMonthCardOrderCommission(orderId,station.getComId(),merchant.getParentId(),parentCommission,
                    parent.getCommissionRate(),RateRemark,MemberEnum.UserType.merchant.name(),sortNo);

            sortNo ++;
        }

        int profit = payAmount - parentCommission - merchantCommission - totalSharingCommission;
        //添加平台收益流水-充电佣金
        if(profit > 0) {

            PlatformProfitBill profitBill = new PlatformProfitBill();
            profitBill.setComId(station.getComId());
            profitBill.setOutTradeNo(outTradeNo);
            profitBill.setOrderNo(orderNo);
            profitBill.setAmount(profit);
            profitBill.setCreateTime(createTime);
            profitBill.setType(FinancialEnum.IncomeOrExpend.Income.name());
            profitBill.setStatus(FinancialEnum.BillStatus.Effective.name());
            profitBill.setEvent(FinancialEnum.PlatformProfitBillEvent.MonthCommission.name());
            profitBill.setNo(StrUtil.builder(cn.hutool.core.date.DateUtil.date().toString(DatePattern.PURE_DATETIME_MS_PATTERN), RandomUtil.randomNumbers(4)).toString());
            platformProfitBillDao.saveRow(profitBill);
        }

        return profit;
    }

    /**
     * 月卡佣金退款
     * @param orderId
     * @param createTime
     * @param orderNo
     * @param outTradeNo
     * @param refundAmount
     * @return 月卡订单利润
     */
    @Override
    public int refundMonthCardCommission(String orderId,String stationId, Date createTime, String orderNo, String outTradeNo, int refundAmount,int payAmount){
        if(refundAmount <= 0)
            return 0;

        Station station = stationDao.getRow(stationId);
        if(station == null){
            return refundAmount;
        }

        String RateRemark = "";
        int sortNo = 1;

        //分成商户
        int totalSharingCommission = 0;
        //分成商户总比例
        double totalSharingRate = 0;
        List<StationSharing> stationSharings = stationSharingDao.getRows(new String[]{"device_station_id"},new Object[]{stationId},new String[]{},new String[]{});
        for(int index = 0;index < stationSharings.size();index ++){
            StationSharing item = stationSharings.get(index);
            double sharingRate = NumberUtil.div(item.getCommissionRate().doubleValue(), 100);

            if (sharingRate >= 0) {

                int sharingCommission = (int)NumberUtil.mul(refundAmount, sharingRate);

                MerchantBill merchantBill = new MerchantBill();
                merchantBill.setPlatformMerchantId(item.getPlatformMerchantId());
                merchantBill.setComId(station.getComId());
                merchantBill.setNo(OrderUtil.getOrderNo());
                merchantBill.setOutTradeNo(outTradeNo);
                merchantBill.setOrderNo(orderNo);
                merchantBill.setAmount(sharingCommission);
                merchantBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());//收入支出类型：0-收入，1-支出
                merchantBill.setEvent(FinancialEnum.MerchantBillEvent.MonthCommissionRefund.name());
                merchantBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
                merchantBill.setCreateTime(createTime);
                merchantBillDao.saveRow(merchantBill);

                totalSharingCommission += sharingCommission;
                totalSharingRate += sharingRate;

                //TODO 记录订单佣金
                RateRemark =  NumberUtil.div(payAmount,100) + " * " + formatRate(sharingRate);

                saveMonthCardOrderCommission(orderId,station.getComId(),item.getPlatformMerchantId(),sharingCommission,
                        item.getCommissionRate(),RateRemark,MemberEnum.UserType.sharing.name(),sortNo);

                sortNo ++;
            }
        }


        //运营商
        int merchantCommission = 0;
        double merchantRate = NumberUtil.div(station.getCommissionRate().doubleValue(), 100);
        if (merchantRate > 0 && !StrUtil.isEmpty(station.getPlatformMerchantId())) {

            merchantCommission = (int)NumberUtil.mul(refundAmount, merchantRate);
            merchantCommission = merchantCommission - totalSharingCommission;


            MerchantBill merchantBill = new MerchantBill();
            merchantBill.setPlatformMerchantId(station.getPlatformMerchantId());
            merchantBill.setComId(station.getComId());
            merchantBill.setNo(OrderUtil.getOrderNo());
            merchantBill.setOutTradeNo(outTradeNo);
            merchantBill.setOrderNo(orderNo);
            merchantBill.setAmount(merchantCommission);
            merchantBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());//收入支出类型：0-收入，1-支出
            merchantBill.setEvent(FinancialEnum.MerchantBillEvent.MonthCommissionRefund.name());
            merchantBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
            merchantBill.setCreateTime(createTime);
            merchantBillDao.saveRow(merchantBill);

            //TODO 记录订单佣金
            RateRemark =  NumberUtil.div(payAmount,100) + " * (" + formatRate(merchantRate) + " - " + formatRate(totalSharingRate) +")";

            saveMonthCardOrderCommission(orderId, station.getComId(),station.getPlatformMerchantId(), merchantCommission,
                    station.getCommissionRate(),RateRemark,MemberEnum.UserType.merchant.name(),sortNo);

            sortNo ++;
        }


        Merchant merchant = merchantDao.getEntity(station.getPlatformMerchantId());
        //上级运营商
        int parentCommission = 0;
        if(!StringUtil.isEmpty(merchant.getParentId())){
            Merchant parent = merchantDao.getEntity(merchant.getParentId());
            double parentRate = NumberUtil.div(parent.getCommissionRate().doubleValue(), 100);
            parentCommission = NumberUtil.sub(NumberUtil.mul(refundAmount, parentRate), merchantCommission, totalSharingCommission).intValue();

            MerchantBill merchantBill = new MerchantBill();
            merchantBill.setPlatformMerchantId(merchant.getParentId());
            merchantBill.setComId(station.getComId());
            merchantBill.setNo(OrderUtil.getOrderNo());
            merchantBill.setOutTradeNo(outTradeNo);
            merchantBill.setOrderNo(orderNo);
            merchantBill.setAmount(parentCommission);
            merchantBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());//收入支出类型：0-收入，1-支出
            merchantBill.setEvent(FinancialEnum.MerchantBillEvent.MonthCommissionRefund.name());
            merchantBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
            merchantBill.setCreateTime(createTime);
            merchantBillDao.saveRow(merchantBill);

            //TODO 记录订单佣金
            RateRemark =  NumberUtil.div(payAmount,100) + " * (" + formatRate(parentRate) + " - " + formatRate(merchantRate) + ")";

            saveMonthCardOrderCommission(orderId,station.getComId(),merchant.getParentId(),parentCommission,
                    parent.getCommissionRate(),RateRemark,MemberEnum.UserType.merchant.name(),sortNo);

            sortNo ++;
        }


        int profit = refundAmount - parentCommission - merchantCommission - totalSharingCommission;
        //添加平台收益流水-充电佣金
        if(profit > 0) {
            PlatformProfitBill profitBill = new PlatformProfitBill();
            profitBill.setComId(station.getComId());
            profitBill.setOutTradeNo(outTradeNo);
            profitBill.setOrderNo(orderNo);
            profitBill.setAmount(profit);
            profitBill.setCreateTime(createTime);
            profitBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());
            profitBill.setStatus(FinancialEnum.BillStatus.Effective.name());
            profitBill.setEvent(FinancialEnum.PlatformProfitBillEvent.MonthCommissionRefund.name());
            profitBill.setNo(StrUtil.builder(cn.hutool.core.date.DateUtil.date().toString(DatePattern.PURE_DATETIME_MS_PATTERN), RandomUtil.randomNumbers(4)).toString());
            platformProfitBillDao.saveRow(profitBill);
        }

        return profit;
    }


    /**
     * 记录月卡订单佣金
     * @param userId orderId 订单ID
     * @param userId 用户ID(代理商、运营商、业务员）
     * @param commission 佣金
     * @param radio 佣金比例
     * @param RateRemark 佣金比例说明
     * @param userType 类型:agent-代理商 merchant-运营商 salesman-业务员
     */
    private void saveMonthCardOrderCommission(String orderId,String comId,String userId,int commission,int radio,String RateRemark,String userType,int sortNo){
        CardOrderCommission entity = cardOrderCommissionDao.getRow(new String[]{"com_id","month_card_order_id","platform_user_id"},new Object[]{comId,orderId,userId});
        if(entity == null){
            entity = new CardOrderCommission();
            entity.setComId(comId);
            entity.setMonthCardOrderId(orderId);
            entity.setPlatformUserId(userId);

            entity.setCommissionRate(radio);
            entity.setRateRemark(RateRemark);
            entity.setUserType(userType);
            entity.setSortNo(sortNo);
            entity.setCommission(commission);
            entity.setCreateTime(DateUtil.date());
        }else{
            if(entity.getRateRemark().startsWith("首次佣金")){
                entity.setRateRemark(entity.getRateRemark() + " - 退款佣金：" + formatRate(commission / 100.0));
            }else {
                entity.setRateRemark("首次佣金：" + formatRate(entity.getCommission() / 100.0) + " - 退款佣金：" + formatRate(commission / 100.0));
            }
            entity.setCommission(entity.getCommission() - commission);
            entity.setCreateTime(DateUtil.date());
        }

        cardOrderCommissionDao.saveRow(entity);
    }
}
